package com.yitongmao.common.reminder;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteReadOnlyDatabaseException;

import com.yitongmao.util.Loger;
import com.yitongmao.yitmfruit.R;

import java.util.ArrayList;
import java.util.List;

public class ReminderDbHelper extends SQLiteOpenHelper {

    // Database name
    private static final String DATABASE_NAME = ReaderApplication.getInstace().getResources().getString(R.string.app_name) + "_db";
    // Database version aligned if possible to software version
    private static final int DATABASE_VERSION = 501;

    // Notes table name
    public static final String TABLE_LIVING = "create table " + DATABASE_NAME + "(fileId int,title varchar(100),alarm varchar(100))";

    // Notes table columns
    public static final String KEY_ID = "creation";
    public static final String KEY_FILEDID = "fileId";
    public static final String KEY_TITLE = "title";
    public static final String KEY_ALARM = "alarm";

    private final Context mContext;
    private static ReminderDbHelper instance = null;
    private SQLiteDatabase db;

    public static synchronized ReminderDbHelper getInstance() {
        return getInstance(ReaderApplication.getInstace().getApplicationContext());
    }

    public static synchronized ReminderDbHelper getInstance(Context context) {
        if (instance == null) {
            instance = new ReminderDbHelper(context);
        }
        return instance;
    }

    public ReminderDbHelper(Context mContext) {
        super(mContext, DATABASE_NAME, null, DATABASE_VERSION);
        this.mContext = mContext;
    }

    public SQLiteDatabase getDatabase() {
        return getDatabase(false);
    }

    public SQLiteDatabase getDatabase(boolean forceWritable) {
        try {
            SQLiteDatabase db = getReadableDatabase();
            if (forceWritable && db.isReadOnly()) {
                throw new SQLiteReadOnlyDatabaseException("Required writable database, obtained read-only");
            }
            return db;
        } catch (IllegalStateException e) {
            return this.db;
        }
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        //建表
        Loger.i("ReminderDbHelper-onCreate", "Database creation");
        db.execSQL(TABLE_LIVING);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }

    public ReminderBean insertLivingReminder(ReminderBean reminderBean) {
        SQLiteDatabase db = getDatabase();
        db.beginTransaction();
        ContentValues values = new ContentValues();
        values.put(KEY_FILEDID, reminderBean.getFileID());
        values.put(KEY_TITLE, reminderBean.getTitle());
        values.put(KEY_ALARM, reminderBean.getAlarm());

//        if (getReminderLiving(reminderBean.getFileId()) != null) {
//            deleteReminderLiving(reminderBean);
//        }

        db.insertWithOnConflict(DATABASE_NAME, KEY_ID, values, SQLiteDatabase.CONFLICT_REPLACE);
        db.setTransactionSuccessful();
        db.endTransaction();
        return reminderBean;
    }

    /**
     * Getting single note
     */
    public ReminderBean getReminderLiving(long id) {

        String whereCondition = " WHERE "
                + KEY_FILEDID + " = " + id;

        List<ReminderBean> notes = getReminderLivings(whereCondition);
        ReminderBean reminderBean;
        if (notes.size() > 0) {
            reminderBean = notes.get(0);
        } else {
            reminderBean = null;
        }
        return reminderBean;
    }

    public List<ReminderBean> getAllReminderLiving() {
        String whereCondition = " WHERE " + KEY_FILEDID + " IS NOT 0"
                + " AND " + KEY_TITLE + " IS NOT NULL";
        return getReminderLivings(whereCondition);
    }

    public List<ReminderBean> getReminderLivings(String whereCondition) {
        List<ReminderBean> reminderBeanList = new ArrayList<>();

        // Generic query to be specialized with conditions passed as parameter
        String query = "SELECT "
                + KEY_FILEDID + ","
                + KEY_TITLE + ","
                + KEY_ALARM
                + " FROM " + DATABASE_NAME
                + whereCondition;


        Cursor cursor = null;
        try {
            cursor = getDatabase().rawQuery(query, null);

            // Looping through all rows and adding to list
            if (cursor != null) {
                if (cursor.moveToFirst()) {
                    do {
                        int i = 0;
                        ReminderBean reminderBean = new ReminderBean();
                        reminderBean.setFileId(cursor.getInt(i++));
                        reminderBean.setTitle(cursor.getString(i++));
                        reminderBean.setAlarm(cursor.getLong(i++));
                        // Adding note to list
                        reminderBeanList.add(reminderBean);

                    } while (cursor.moveToNext());
                }
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        Loger.v("getNotes", "Query: Retrieval finished!");
        return reminderBeanList;
    }

    public boolean deleteReminderLiving(ReminderBean reminderBean) {
        int deletedNotes;
        boolean result = true;
        SQLiteDatabase db = getDatabase(true);
        // Delete notes
        deletedNotes = db.delete(DATABASE_NAME, KEY_FILEDID + " = ?", new String[]{String.valueOf(reminderBean.getFileID())});
        // Check on correct and complete deletion
        result = (deletedNotes == 1);
        return result;
    }

}
